package com.ljh.controller;

import com.ljh.utils.QinniuUtils;
import com.ljh.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@Api(description = "上传接口管理")
@CrossOrigin
public class UploadController {

    @Autowired
    QinniuUtils qinniuUtils;


    /**
     * 七牛云上传图片
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ApiOperation("向七牛云上传")
    public Result upload(@RequestParam("file")MultipartFile file){
        //原始文件名称 比如aa.png
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        //唯一文件名称
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, "."); //构成文件名称 UUID唯一确定
        //上传文件,上传到哪里? 上传到云服务器 按量付费 把图片发放到离用户最近的服务器
        System.out.println(fileName);
        //降低我们自身应用服务器的资源
        boolean upload = qinniuUtils.upload(file, fileName);
        if(upload){
            return Result.success(QinniuUtils.url+fileName);
        }
        return Result.fail(20001,"上传失败");
    }

}